<?php

class Products_DbController extends FinalView_Controller_Action
{
    
    /**
    * Products
    * 
    * @var Products
    */
    private $_model_products;
    
    /**
    * Content
    * 
    * @var Content
    */
    private $_model_content;
    
    /**
    * Products_Form_Product
    * 
    * @var Products_Form_Product
    */
    private $_form_products;
    
    public function init()
    {
        parent::init();
        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('is-exist', 'json')->initContext();
        
        $this->_model_products = new Products;
        $this->_model_content = new Content;
        
        $this->_form_products = new Products_Form_Product;
        
        
        // alphabet filter
        $letter = $this->_getParam('letter', '');
        $alphabet = $this->_model_products->getAlphabet();
        if ($letter && !in_array($letter, $alphabet)) {
            $this->abort('В БД нет продуктов начинающихся с буквы ', 
                $this->view->escape($letter));
        }
        $this->view->alphabet = array(
            'values' => $alphabet, 
            'value' => $letter, 
        );
        
        if (in_array($this->getRequest()->getActionName(), array('index', 'edit'))) 
        {
            $page = $this->_getParam('page', 1);
            
            $pager = $this->_model_content->getContentList($page, $letter);
            $pager_range = $pager->getRange('Sliding', array('chunk' => 5));
            
            if (!$pager_range->isInRange($page)) {
                $this->abort('Page is not in range');
            }
            
            $this->view->pager_range = $pager_range;
            $this->view->pager = $pager;
            
            $model_components = new Components;
            $this->view->components = $model_components->getOptions();
        }
    }
    
    const PRODUCT_EXISTS = '<strong>%s</strong> - продукт уже сохранен в БД';
    
    public function isExistAction() 
    {
        if ($record = Doctrine::getTable('Products')
            ->findOneByName($this->_getParam('name'))) 
        {
            $this->view->assign(array(
                'status' => true, 
                'message' => sprintf(self::PRODUCT_EXISTS, 
                    $this->view->escape($this->_getParam('name'))), 
                'product' => array
                    (
                        'name' => $this->view->escape($this->_getParam('name')), 
                        'content' => $record->Content->toArray()
                    ), 
            ));
        } else {
            $this->view->status = false;
        }
    }
    
    public function indexAction()
    {
        $this->_forward('add');
    }
    
    public function editAction() 
    {
        $collection = $this->_model_content->getContent($this->_getParam('id'));
        if (!$collection->count()) {
            $this->abort('Нет такого продукта');
        }
        
        if ($this->getRequest()->isGet()) {
            $product = array
            (
                'id' => $collection[0]->id, 
                'name' => $collection[0]->name
            );
            foreach ($collection[0]['Content']->toArray() as $component) {
                $product['component_' . $component['component_code']] = 
                    $component['value'];
            }
            $this->_form_products->populate($product);
        }
        
        $this->addAction();
    }
    
    public function addAction() 
    {
        if ($this->getRequest()->isPost()) {
            if ($this->_form_products->isValid($this->getRequest()->getPost())) {
                $this->_model_products->addProduct($this->_form_products->getValues());
                
                $this->getHelper('FlashMessenger')->addMessage('Сохранено');
                $this->_redirect($this->getRequest()->getRequestUri());
            }
        }
        
        $this->_form_products->setAction($this->getRequest()->getRequestUri());
        $this->view->form = $this->_form_products;
    }
    
    public function deleteAction() 
    {
        if (count($delete = array_filter($this->_getParam('delete')))) {
            $this->_model_products->deleteProducts(array_keys($delete));
        }
        
        $this->getHelper('FlashMessenger')->addMessage('Удалено');
        $this->_helper->redirector->gotoRoute(array(), 'Products');
    }
    
    public function autocompleteListAction() 
    {
        echo implode(',', $this->_model_products->getProducts());
        exit;
    }
    
}

